package com.mutouren.web.org;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mutouren.common.entity.PageInfo;
import com.mutouren.common.entity.ValidState;
import com.mutouren.common.web.BootStrapPage;
import com.mutouren.common.web.ParsePageInfo;
import com.mutouren.modules.org.model.Organization;
import com.mutouren.modules.org.model.Role;
import com.mutouren.modules.org.service.OrganizationService;
import com.mutouren.modules.org.service.RoleService;
import com.mutouren.web.WebUtils;

@Controller
@RequestMapping(value="/org/grant")
public class OrganizationGrantAction {
	
	@Resource
	private OrganizationService organizationService;	
	
	@Resource
	private RoleService roleService;		
	
	@RequestMapping(value="/manage.action")
	public String manage(HttpServletRequest request) {
		PageInfo pageInfo = ParsePageInfo.parse(request);
		List<Role> listRole = new ArrayList<Role>();
		request.setAttribute("listRole", listRole);

		List<Organization> listOrganization = organizationService.getChildren(Organization.ROOT_ID, true, true, false, ValidState.Normal);		
		request.setAttribute("listOrganization", OrgUtils.convertOrganizationToJSON(listOrganization));					
		request.setAttribute("mtrPage", BootStrapPage.buildHtmlPage(pageInfo));		
		
		return "modules/org/organizationGrantList";
	}
	
	@RequestMapping(value="/add.action")
	public void add(@RequestParam(value="orgId") int orgId,
			@RequestParam(value="roleId") int roleId,
			HttpServletResponse response) throws IOException {

		if (roleService.addToOrg(orgId, roleId) == 0) {
			WebUtils.successDialog(response);
		} else {
			WebUtils.failDialog(response, "角色已存在");
		}
	}	
	
	@RequestMapping(value="/delete.action")
	public void delete(@RequestParam(value="orgId") int orgId,
			@RequestParam(value="roleId") int roleId,
			HttpServletResponse response) throws IOException {

		roleService.removeFromOrg(orgId, roleId);
		response.getWriter().write("success");
	}

	@RequestMapping(value="/grid.action")
	public String grid(@RequestParam(value="orgId") int orgId,
			@RequestParam(value="isInherit") boolean isInherit,
			HttpServletRequest request) {
		PageInfo pageInfo = ParsePageInfo.parse(request);
		List<Role> listRole = roleService.selectByOrgId(orgId, isInherit, pageInfo);
		request.setAttribute("listRole", listRole);
		request.setAttribute("mtrPage", BootStrapPage.buildHtmlPage(pageInfo));
		
		return "modules/org/organizationGrantGrid";
	}
	
}
